<template>
  <div class="user-management-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">
          <el-icon><User /></el-icon>
          用户管理
        </h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="header-right">
        <el-button-group>
          <el-button 
            type="primary" 
            @click="showCreateUserDialog"
            v-if="authStore.hasPermission(PERMISSIONS.USER_MANAGE)"
          >
            <el-icon><Plus /></el-icon>
            添加用户
          </el-button>
          <el-button @click="refreshUsers">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button 
            @click="showImportDialog"
            v-if="authStore.hasPermission(PERMISSIONS.USER_MANAGE)"
          >
            <el-icon><Upload /></el-icon>
            导入用户
          </el-button>
          <el-button 
            @click="exportUsers"
            v-if="authStore.hasPermission(PERMISSIONS.REPORT_VIEW)"
          >
            <el-icon><Download /></el-icon>
            导出用户
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.totalUsers }}</div>
            <div class="stat-label">总用户数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon admin">
            <el-icon><UserFilled /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.adminUsers }}</div>
            <div class="stat-label">管理员</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon agent">
            <el-icon><Service /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.agentUsers }}</div>
            <div class="stat-label">客服</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card">
        <div class="stat-content">
          <div class="stat-icon customer">
            <el-icon><Avatar /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.customerUsers }}</div>
            <div class="stat-label">客户</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 筛选工具栏 -->
    <el-card class="filter-card">
      <div class="filter-toolbar">
        <div class="filter-left">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索用户名、姓名或邮箱"
            clearable
            @input="handleSearch"
            style="width: 300px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select
            v-model="roleFilter"
            placeholder="角色筛选"
            clearable
            @change="handleFilter"
            style="width: 120px; margin-left: 12px;"
          >
            <el-option label="全部角色" value="" />
            <el-option label="管理员" value="admin" />
            <el-option label="经理" value="manager" />
            <el-option label="客服" value="agent" />
            <el-option label="客户" value="customer" />
          </el-select>
          
          <el-select
            v-model="statusFilter"
            placeholder="状态筛选"
            clearable
            @change="handleFilter"
            style="width: 120px; margin-left: 12px;"
          >
            <el-option label="全部状态" value="" />
            <el-option label="激活" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
          
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleFilter"
            style="width: 240px; margin-left: 12px;"
          />
        </div>
        
        <div class="filter-right">
          <el-button @click="resetFilters">重置筛选</el-button>
          <el-button type="primary" @click="applyFilters">应用筛选</el-button>
        </div>
      </div>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="user-list-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <div class="header-actions">
            <el-button-group>
              <el-button 
                :type="viewMode === 'table' ? 'primary' : ''"
                @click="viewMode = 'table'"
              >
                <el-icon><Grid /></el-icon>
                表格视图
              </el-button>
              <el-button 
                :type="viewMode === 'card' ? 'primary' : ''"
                @click="viewMode = 'card'"
              >
                <el-icon><Menu /></el-icon>
                卡片视图
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <!-- 表格视图 -->
      <el-table
        v-if="viewMode === 'table'"
        :data="paginatedUsers"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        :default-sort="{ prop: 'createdAt', order: 'descending' }"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="用户ID" width="100" sortable="custom" />
        <el-table-column prop="username" label="用户名" width="120" sortable="custom" />
        <el-table-column prop="name" label="姓名" width="120" sortable="custom" />
        <el-table-column prop="email" label="邮箱" min-width="200" show-overflow-tooltip />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)" size="small">
              {{ translateRole(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="isUserActive(row) ? 'success' : 'danger'" size="small">
              {{ isUserActive(row) ? '激活' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160" sortable="custom">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginAt" label="最后登录" width="160" sortable="custom">
          <template #default="{ row }">
            {{ formatDateTime(row.lastLoginAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button size="small" @click="viewUserDetail(row)">
                查看
              </el-button>
              <el-button 
                size="small" 
                @click="editUser(row)"
                v-if="authStore.hasPermission(PERMISSIONS.USER_MANAGE)"
              >
                编辑
              </el-button>
              <el-button 
                size="small" 
                @click="editPermissions(row)"
                v-if="authStore.hasPermission(PERMISSIONS.USER_MANAGE)"
              >
                权限
              </el-button>
              <el-button 
                size="small" 
                :type="isUserActive(row) ? 'warning' : 'success'"
                @click="toggleUserStatus(row)"
                v-if="authStore.hasPermission(PERMISSIONS.USER_MANAGE)"
              >
                {{ isUserActive(row) ? '禁用' : '启用' }}
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="deleteUser(row)"
                v-if="authStore.hasPermission(PERMISSIONS.USER_MANAGE) && row.id !== authStore.user?.id"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 卡片视图 -->
      <div v-else class="card-view">
        <div 
          v-for="user in paginatedUsers" 
          :key="user.id"
          class="user-card"
        >
          <div class="card-header">
            <div class="user-avatar">
              <el-avatar :size="50" :src="user.avatar">
                {{ (user.fullName || user.name || user.username || 'U').charAt(0) }}
              </el-avatar>
            </div>
            <div class="user-info">
              <div class="user-name">{{ user.fullName || user.name || user.username }}</div>
              <div class="user-username">@{{ user.username }}</div>
            </div>
            <div class="user-status">
              <el-tag :type="getRoleType(user.role)" size="small">
                {{ translateRole(user.role) }}
              </el-tag>
              <el-tag :type="isUserActive(user) ? 'success' : 'danger'" size="small" style="margin-top: 4px;">
                {{ isUserActive(user) ? '激活' : '禁用' }}
              </el-tag>
            </div>
          </div>
          
          <div class="user-details">
            <div class="detail-item">
              <el-icon><Message /></el-icon>
              <span>{{ user.email }}</span>
            </div>
            <div class="detail-item">
              <el-icon><Clock /></el-icon>
              <span>创建于 {{ formatDate(user.createdAt) }}</span>
            </div>
            <div class="detail-item" v-if="user.lastLoginAt">
              <el-icon><Timer /></el-icon>
              <span>最后登录 {{ formatDate(user.lastLoginAt) }}</span>
            </div>
          </div>
          
          <div class="card-actions">
            <el-button size="small" @click="viewUserDetail(user)">
              查看详情
            </el-button>
            <el-button 
              size="small" 
              @click="editUser(user)"
              v-if="authStore.hasPermission(PERMISSIONS.USER_MANAGE)"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              @click="editPermissions(user)"
              v-if="authStore.hasPermission(PERMISSIONS.USER_MANAGE)"
            >
              权限
            </el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredUsers.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 批量操作工具栏 -->
    <el-card v-if="selectedUsers.length > 0" class="batch-actions-card">
      <div class="batch-actions">
        <span class="selected-count">已选择 {{ selectedUsers.length }} 个用户</span>
        <el-button-group>
          <el-button 
            @click="batchUpdateRole"
            v-if="authStore.hasPermission(PERMISSIONS.USER_MANAGE)"
          >
            <el-icon><User /></el-icon>
            批量修改角色
          </el-button>
          <el-button 
            @click="batchUpdateStatus"
            v-if="authStore.hasPermission(PERMISSIONS.USER_MANAGE)"
          >
            <el-icon><Switch /></el-icon>
            批量修改状态
          </el-button>
          <el-button 
            @click="batchDelete"
            type="danger"
            v-if="authStore.hasPermission(PERMISSIONS.USER_MANAGE)"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </el-button-group>
      </div>
    </el-card>

    <!-- 创建/编辑用户对话框 -->
    <el-dialog
      v-model="userDialog.visible"
      :title="userDialog.isEdit ? '编辑用户' : '添加用户'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="fullName">
              <el-input v-model="userForm.fullName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号（可选）" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="!userDialog.isEdit">
          <el-input 
            v-model="userForm.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword" v-if="!userDialog.isEdit">
          <el-input 
            v-model="userForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword" v-if="userDialog.isEdit">
          <el-input 
            v-model="userForm.newPassword" 
            type="password" 
            placeholder="留空则不修改密码"
            show-password
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%">
                <el-option label="管理员" value="ADMIN" />
                <el-option label="主管" value="SUPERVISOR" />
                <el-option label="客服" value="AGENT" />
                <el-option label="客户" value="CUSTOMER" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="userForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="激活" value="ACTIVE" />
                <el-option label="非活跃" value="INACTIVE" />
                <el-option label="暂停" value="SUSPENDED" />
                <el-option label="待审核" value="PENDING" />
                <el-option label="锁定" value="LOCKED" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="userDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitUser">
          {{ userDialog.isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="userDetailDialog.visible"
      title="用户详情"
      width="500px"
    >
      <div v-if="selectedUser" class="user-detail-content">
        <div class="user-profile">
          <el-avatar :size="80" :src="selectedUser.avatar">
            {{ (selectedUser.fullName || selectedUser.name || selectedUser.username || 'U').charAt(0) }}
          </el-avatar>
          <div class="profile-info">
            <h3>{{ selectedUser.fullName || selectedUser.name || selectedUser.username }}</h3>
            <p>@{{ selectedUser.username }}</p>
            <el-tag :type="getRoleType(selectedUser.role)">
              {{ translateRole(selectedUser.role) }}
            </el-tag>
          </div>
        </div>
        
        <el-divider />
        
        <div class="user-details">
          <div class="detail-row">
            <span class="label">邮箱：</span>
            <span class="value">{{ selectedUser.email }}</span>
          </div>
          <div class="detail-row">
            <span class="label">状态：</span>
            <el-tag :type="isUserActive(selectedUser) ? 'success' : 'danger'">
              {{ isUserActive(selectedUser) ? '激活' : '禁用' }}
            </el-tag>
          </div>
          <div class="detail-row">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatDateTime(selectedUser.createdAt) }}</span>
          </div>
          <div class="detail-row" v-if="selectedUser.lastLoginAt">
            <span class="label">最后登录：</span>
            <span class="value">{{ formatDateTime(selectedUser.lastLoginAt) }}</span>
          </div>
        </div>
        
        <el-divider />
        
        <div class="user-permissions">
          <h4>权限列表</h4>
          <div class="permission-tags">
            <el-tag 
              v-for="permission in selectedUser.permissions" 
              :key="permission"
              size="small"
              style="margin: 2px;"
            >
              {{ translatePermission(permission) }}
            </el-tag>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="userDetailDialog.visible = false">关闭</el-button>
        <el-button 
          type="primary" 
          @click="editUser(selectedUser)"
          v-if="authStore.hasPermission(PERMISSIONS.USER_MANAGE)"
        >
          编辑用户
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限编辑对话框 -->
    <el-dialog
      v-model="permissionDialog.visible"
      title="编辑用户权限"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="selectedUser" class="permission-content">
        <div class="user-info">
          <el-icon class="user-icon"><User /></el-icon>
          <div class="user-details">
            <div class="user-name">{{ selectedUser.fullName || selectedUser.name || selectedUser.username }}</div>
            <div class="user-role">{{ translateRole(selectedUser.role) }}</div>
          </div>
        </div>
        
        <el-divider />
        
        <div class="permission-sections">
          <div class="permission-section">
            <h4>工单权限</h4>
            <el-checkbox-group v-model="permissionForm.permissions">
              <el-checkbox value="ticket:read">查看工单</el-checkbox>
              <el-checkbox value="ticket:create">创建工单</el-checkbox>
              <el-checkbox value="ticket:update">更新工单</el-checkbox>
              <el-checkbox value="ticket:delete">删除工单</el-checkbox>
              <el-checkbox value="ticket:assign">指派工单</el-checkbox>
            </el-checkbox-group>
          </div>
          
          <div class="permission-section">
            <h4>用户管理权限</h4>
            <el-checkbox-group v-model="permissionForm.permissions">
              <el-checkbox value="user:manage">用户管理</el-checkbox>
            </el-checkbox-group>
          </div>
          
          <div class="permission-section">
            <h4>系统权限</h4>
            <el-checkbox-group v-model="permissionForm.permissions">
              <el-checkbox value="system:config">系统配置</el-checkbox>
              <el-checkbox value="report:view">报表查看</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="permissionDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="updatingPermissions" @click="confirmUpdatePermissions">
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 批量修改角色对话框 -->
    <el-dialog
      v-model="batchRoleDialog.visible"
      title="批量修改角色"
      width="400px"
    >
      <el-form label-width="80px">
        <el-form-item label="角色">
          <el-select v-model="batchRoleDialog.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" value="admin" />
            <el-option label="经理" value="manager" />
            <el-option label="客服" value="agent" />
            <el-option label="客户" value="customer" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchRoleDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchRole">确认修改</el-button>
      </template>
    </el-dialog>

    <!-- 批量修改状态对话框 -->
    <el-dialog
      v-model="batchStatusDialog.visible"
      title="批量修改状态"
      width="400px"
    >
      <el-form label-width="80px">
        <el-form-item label="状态">
          <el-select v-model="batchStatusDialog.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="激活" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchStatusDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchStatus">确认修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, reactive } from 'vue'
import { useUserStore } from '../store/user'
import { useAuthStore, PERMISSIONS } from '../store/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, UserFilled, Service, Avatar, Plus, Refresh, Upload, Download,
  Search, Grid, Menu, Message, Clock, Timer, Switch, Delete
} from '@element-plus/icons-vue'

export default {
  name: 'UserManagement',
  components: {
    User, UserFilled, Service, Avatar, Plus, Refresh, Upload, Download,
    Search, Grid, Menu, Message, Clock, Timer, Switch, Delete
  },
  setup() {
    const userStore = useUserStore()
    const authStore = useAuthStore()

    // 响应式数据
    const loading = ref(false)
    const searchKeyword = ref('')
    const roleFilter = ref('')
    const statusFilter = ref('')
    
    // 辅助函数：判断用户是否激活
    const isUserActive = (user) => {
      if (user.status) {
        return user.status === 'ACTIVE'
      }
      // 兼容旧数据格式
      return user.active === true
    }
    const dateRange = ref([])
    const viewMode = ref('table')
    const currentPage = ref(1)
    const pageSize = ref(20)
    const selectedUsers = ref([])
    const submitting = ref(false)
    const updatingPermissions = ref(false)

    // 对话框状态
    const userDialog = ref({ visible: false, isEdit: false })
    const userFormRef = ref(null)
    const userDetailDialog = ref({ visible: false })
    const permissionDialog = ref({ visible: false })
    const batchRoleDialog = ref({ visible: false, role: '' })
    const batchStatusDialog = ref({ visible: false, status: true })

    // 表单数据
    const userForm = reactive({
      id: null,
      username: '',
      fullName: '',
      email: '',
      phone: '',
      password: '',
      confirmPassword: '',
      newPassword: '',
      role: 'CUSTOMER',
      status: 'ACTIVE'
    })

    const permissionForm = reactive({
      permissions: []
    })

    const selectedUser = ref(null)

    // 表单验证规则
    const userRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      fullName: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { 
          validator: (rule, value, callback) => {
            if (value !== userForm.password) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          }, 
          trigger: 'blur' 
        }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ]
    }

    // 计算属性
    const stats = computed(() => {
      // 安全检查：确保users是数组
      const users = Array.isArray(userStore.users) ? userStore.users : []
      
      return {
        totalUsers: users.length,
        adminUsers: users.filter(u => u.role === 'ADMIN' || u.role === 'admin').length,
        agentUsers: users.filter(u => u.role === 'AGENT' || u.role === 'agent').length,
        customerUsers: users.filter(u => u.role === 'CUSTOMER' || u.role === 'customer').length
      }
    })

    const filteredUsers = computed(() => {
      // 安全检查：确保users是数组
      let users = Array.isArray(userStore.users) ? userStore.users : []

      // 搜索筛选
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        users = users.filter(user => 
          user.username?.toLowerCase().includes(keyword) ||
          (user.fullName || user.name || '').toLowerCase().includes(keyword) ||
          user.email?.toLowerCase().includes(keyword)
        )
      }

      // 角色筛选
      if (roleFilter.value) {
        users = users.filter(user => user.role === roleFilter.value)
      }

      // 状态筛选
      if (statusFilter.value) {
        users = users.filter(user => {
          const active = isUserActive(user)
          return statusFilter.value === 'active' ? active : !active
        })
      }

      // 日期范围筛选
      if (dateRange.value && dateRange.value.length === 2) {
        const [startDate, endDate] = dateRange.value
        users = users.filter(user => {
          const userDate = new Date(user.createdAt)
          return userDate >= startDate && userDate <= endDate
        })
      }

      return users
    })

    const paginatedUsers = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredUsers.value.slice(start, end)
    })

    // 方法
    // 防抖：避免频繁刷新
    let refreshTimer = null
    const refreshUsers = async () => {
      // 清除之前的定时器
      if (refreshTimer) {
        clearTimeout(refreshTimer)
      }
      
      // 300ms防抖
      return new Promise((resolve) => {
        refreshTimer = setTimeout(async () => {
          loading.value = true
          try {
            await userStore.fetchUsers()
            resolve()
          } catch (error) {
            console.error('刷新用户列表失败:', error)
            // 429错误特殊处理
            if (error.message && error.message.includes('过于频繁')) {
              ElMessage.warning('请求过于频繁，请稍后再试')
            }
            resolve()
          } finally {
            loading.value = false
          }
        }, 300)
      })
    }

    const handleSearch = () => {
      currentPage.value = 1
    }

    const handleFilter = () => {
      currentPage.value = 1
    }

    const resetFilters = () => {
      searchKeyword.value = ''
      roleFilter.value = ''
      statusFilter.value = ''
      dateRange.value = []
      currentPage.value = 1
    }

    const applyFilters = () => {
      currentPage.value = 1
    }

    const handleSelectionChange = (selection) => {
      selectedUsers.value = selection
    }

    const handleSortChange = ({ prop, order }) => {
      console.log('Sort:', prop, order)
    }

    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
    }

    const handleCurrentChange = (page) => {
      currentPage.value = page
    }

    const showCreateUserDialog = () => {
      userDialog.value = { visible: true, isEdit: false }
      resetUserForm()
    }

    const editUser = (user) => {
      userDialog.value = { visible: true, isEdit: true }
      Object.assign(userForm, {
        id: user.id,
        username: user.username,
        fullName: user.fullName || user.name,
        email: user.email,
        phone: user.phone || '',
        password: '',
        confirmPassword: '',
        newPassword: '',
        role: user.role ? user.role.toUpperCase() : 'CUSTOMER',
        status: user.status || (user.active ? 'ACTIVE' : 'INACTIVE')
      })
    }

    const viewUserDetail = (user) => {
      selectedUser.value = user
      userDetailDialog.value.visible = true
    }

    const editPermissions = (user) => {
      selectedUser.value = user
      permissionForm.permissions = [...(user.permissions || [])]
      permissionDialog.value.visible = true
    }

    const resetUserForm = () => {
      Object.assign(userForm, {
        id: null,
        username: '',
        fullName: '',
        email: '',
        phone: '',
        password: '',
        confirmPassword: '',
        newPassword: '',
        role: 'CUSTOMER',
        status: 'ACTIVE'
      })
    }

    const submitUser = async () => {
      if (!userFormRef.value) return
      
      try {
        await userFormRef.value.validate()
        submitting.value = true
        
        if (userDialog.value.isEdit) {
          const updateData = {
            username: userForm.username,
            fullName: userForm.fullName,
            email: userForm.email,
            phone: userForm.phone || '',
            role: userForm.role,
            status: userForm.status
          }
          if (userForm.newPassword) {
            updateData.password = userForm.newPassword
          }
          
          await userStore.updateUser(userForm.id, updateData)
          ElMessage.success('用户更新成功')
        } else {
          // 创建用户时需要包含confirmPassword
          // 确保role和status都是大写的英文枚举值
          const createData = {
            username: userForm.username?.trim() || '',
            fullName: userForm.fullName?.trim() || '',
            email: userForm.email?.trim() || '',
            phone: userForm.phone?.trim() || '', // 空字符串，不是null，因为后端Pattern验证接受空字符串
            password: userForm.password || '',
            confirmPassword: userForm.confirmPassword || '',
            role: userForm.role ? userForm.role.toUpperCase() : 'CUSTOMER',
            status: userForm.status ? userForm.status.toUpperCase() : 'ACTIVE'
          }
          
          // 验证必填字段
          if (!createData.username || createData.username.length < 3) {
            ElMessage.error('用户名不能为空且长度至少3个字符')
            return
          }
          if (!createData.fullName) {
            ElMessage.error('真实姓名不能为空')
            return
          }
          if (!createData.email) {
            ElMessage.error('邮箱不能为空')
            return
          }
          if (!createData.password || createData.password.length < 6) {
            ElMessage.error('密码不能为空且长度至少6个字符')
            return
          }
          if (!createData.confirmPassword) {
            ElMessage.error('确认密码不能为空')
            return
          }
          if (createData.password !== createData.confirmPassword) {
            ElMessage.error('两次输入的密码不一致')
            return
          }
          
          console.log('📤 创建用户数据:', createData)
          const newUser = await userStore.createUser(createData)
          console.log('✅ 创建用户成功，新用户:', newUser)
          
          ElMessage.success('用户创建成功')
          userDialog.value.visible = false
          
          // 重置表单
          resetUserForm()
          
          // 重置筛选条件，确保新用户可见
          searchKeyword.value = ''
          roleFilter.value = ''
          statusFilter.value = ''
          currentPage.value = 1
          
          // 刷新用户列表，确保新用户显示
          await refreshUsers()
          
          // 等待一下，确保列表已更新
          await new Promise(resolve => setTimeout(resolve, 100))
          
          // 如果新用户存在，滚动到列表顶部（新用户应该在顶部）
          if (newUser && userStore.users.length > 0) {
            console.log('✅ 用户列表已刷新，当前用户数:', userStore.users.length)
          }
        }
      } catch (error) {
        console.error('提交失败:', error)
        const errorMessage = error.message || error.response?.data?.message || error.toString()
        ElMessage.error('操作失败：' + errorMessage)
      } finally {
        submitting.value = false
      }
    }

    const toggleUserStatus = async (user) => {
      try {
        // 切换用户状态
        const currentActive = isUserActive(user)
        const newStatus = currentActive ? 'INACTIVE' : 'ACTIVE'
        await userStore.updateUser(user.id, { status: newStatus })
        ElMessage.success(`用户已${newStatus === 'ACTIVE' ? '启用' : '禁用'}`)
        await refreshUsers()
      } catch (error) {
        ElMessage.error('操作失败：' + error.message)
      }
    }

    const deleteUser = async (user) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除用户 ${user.fullName || user.name || user.username} 吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await userStore.deleteUser(user.id)
        ElMessage.success('用户删除成功')
        await refreshUsers()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败：' + error.message)
        }
      }
    }

    const confirmUpdatePermissions = async () => {
      if (!selectedUser.value) return
      
      try {
        updatingPermissions.value = true
        await userStore.updateUserPermissions(
          selectedUser.value.id, 
          permissionForm.permissions
        )
        
        ElMessage.success('权限更新成功')
        permissionDialog.value.visible = false
        await refreshUsers()
      } catch (error) {
        ElMessage.error('权限更新失败：' + error.message)
      } finally {
        updatingPermissions.value = false
      }
    }

    const batchUpdateRole = () => {
      batchRoleDialog.value = { visible: true, role: '' }
    }

    const confirmBatchRole = async () => {
      try {
        const role = batchRoleDialog.value.role
        if (!role) {
          ElMessage.warning('请选择角色')
          return
        }

        await userStore.batchUpdateRole(selectedUsers.value.map(u => u.id), role)
        ElMessage.success('批量修改角色成功')
        batchRoleDialog.value.visible = false
        selectedUsers.value = []
        await refreshUsers()
      } catch (error) {
        ElMessage.error('批量修改失败：' + error.message)
      }
    }

    const batchUpdateStatus = () => {
      batchStatusDialog.value = { visible: true, status: true }
    }

    const confirmBatchStatus = async () => {
      try {
        const status = batchStatusDialog.value.status

        await userStore.batchUpdateStatus(selectedUsers.value.map(u => u.id), status)
        ElMessage.success('批量修改状态成功')
        batchStatusDialog.value.visible = false
        selectedUsers.value = []
        await refreshUsers()
      } catch (error) {
        ElMessage.error('批量修改失败：' + error.message)
      }
    }

    const batchDelete = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
          '确认批量删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await userStore.batchDelete(selectedUsers.value.map(u => u.id))
        ElMessage.success('批量删除成功')
        selectedUsers.value = []
        await refreshUsers()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('批量删除失败：' + error.message)
        }
      }
    }

    const showImportDialog = () => {
      ElMessage.info('导入功能开发中...')
    }

    const exportUsers = () => {
      ElMessage.info('导出功能开发中...')
    }

    // 工具方法
    const getRoleType = (role) => {
      const roleUpper = role ? role.toUpperCase() : ''
      const types = {
        'ADMIN': 'danger',
        'admin': 'danger',
        'SUPERVISOR': 'warning',
        'supervisor': 'warning',
        'manager': 'warning',
        'AGENT': 'primary',
        'agent': 'primary',
        'CUSTOMER': 'info',
        'customer': 'info'
      }
      return types[roleUpper] || types[role] || 'info'
    }

    const translateRole = (role) => {
      const roleMap = {
        'ADMIN': '管理员',
        'admin': '管理员',
        'SUPERVISOR': '主管',
        'supervisor': '主管',
        'manager': '主管',
        'AGENT': '客服',
        'agent': '客服',
        'CUSTOMER': '客户',
        'customer': '客户'
      }
      return roleMap[role] || role
    }

    const translatePermission = (permission) => {
      const permissionMap = {
        'ticket:read': '查看工单',
        'ticket:create': '创建工单',
        'ticket:update': '更新工单',
        'ticket:delete': '删除工单',
        'ticket:assign': '指派工单',
        'user:manage': '用户管理',
        'system:config': '系统配置',
        'report:view': '报表查看'
      }
      return permissionMap[permission] || permission
    }

    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN')
    }

    const formatDate = (dateTime) => {
      if (!dateTime) return '-'
      const date = new Date(dateTime)
      return date.toLocaleDateString('zh-CN')
    }

    // 生命周期
    onMounted(async () => {
      loading.value = true
      try {
        await userStore.fetchUsers()
      } catch (error) {
        console.error('Failed to load users:', error)
      } finally {
        loading.value = false
      }
    })

    return {
      loading,
      searchKeyword,
      roleFilter,
      statusFilter,
      dateRange,
      viewMode,
      currentPage,
      pageSize,
      selectedUsers,
      submitting,
      updatingPermissions,
      userDialog,
      userFormRef,
      userDetailDialog,
      permissionDialog,
      batchRoleDialog,
      batchStatusDialog,
      userForm,
      permissionForm,
      selectedUser,
      userRules,
      stats,
      filteredUsers,
      paginatedUsers,
      isUserActive,
      refreshUsers,
      handleSearch,
      handleFilter,
      resetFilters,
      applyFilters,
      handleSelectionChange,
      handleSortChange,
      handleSizeChange,
      handleCurrentChange,
      showCreateUserDialog,
      editUser,
      viewUserDetail,
      editPermissions,
      submitUser,
      toggleUserStatus,
      deleteUser,
      confirmUpdatePermissions,
      batchUpdateRole,
      confirmBatchRole,
      batchUpdateStatus,
      confirmBatchStatus,
      batchDelete,
      showImportDialog,
      exportUsers,
      getRoleType,
      translateRole,
      translatePermission,
      formatDateTime,
      formatDate,
      authStore,
      PERMISSIONS
    }
  }
}
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.stat-icon.total { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.stat-icon.admin { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.stat-icon.agent { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.stat-icon.customer { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.filter-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-left {
  display: flex;
  align-items: center;
}

.user-list-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.card-view {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 16px;
}

.user-card {
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  padding: 16px;
  background: white;
  transition: all 0.3s ease;
}

.user-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  transform: translateY(-2px);
}

.user-card .card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.user-username {
  font-size: 14px;
  color: #909399;
}

.user-status {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.user-details {
  margin-bottom: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.batch-actions-card {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.selected-count {
  font-weight: 500;
  color: #303133;
}

.user-detail-content {
  padding: 20px 0;
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.profile-info h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  color: #303133;
}

.profile-info p {
  margin: 0 0 8px 0;
  color: #909399;
}

.user-details .detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.user-details .detail-row:last-child {
  border-bottom: none;
}

.user-details .label {
  font-weight: 500;
  color: #606266;
}

.user-details .value {
  color: #303133;
}

.user-permissions h4 {
  margin: 0 0 12px 0;
  color: #303133;
}

.permission-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.permission-content {
  padding: 20px 0;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.user-icon {
  font-size: 24px;
  color: #409eff;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.user-role {
  font-size: 14px;
  color: #909399;
}

.permission-sections {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.permission-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
}

.permission-section .el-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

@media (max-width: 768px) {
  .user-management-container {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .filter-toolbar {
    flex-direction: column;
    gap: 12px;
  }
  
  .filter-left {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .card-view {
    grid-template-columns: 1fr;
  }
}
</style>